import { store } from "@/store";
import { defineStore } from "pinia";
import CouponAPI, {
  type CouponType,
  type CouponForm,
  type CouponListQuery,
} from "@/api/coupon/coupon";

export const useCouponStore = defineStore("coupon", () => {
  const list = ref<CouponType[]>([]);
  const totalCount = ref(0);
  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
  });

  async function fetchList(params: CouponListQuery) {
    loading.list = true;
    try {
      const res = await CouponAPI.getCouponList(params);
      list.value = res.records;
      totalCount.value = res.total_count;
      totalPage.value = res.total_page;
    } finally {
      loading.list = false;
    }
  }

  async function fetchCreate(data: Partial<CouponForm>) {
    loading.create = true;
    try {
      await CouponAPI.createCoupon(data);
    } finally {
      loading.create = false;
    }
  }

  async function fetchUpdate(data: Partial<CouponForm>) {
    loading.update = true;
    try {
      await CouponAPI.updateCoupon(data);
    } finally {
      loading.update = false;
    }
  }

  async function fetchDelete(id: number) {
    loading.delete = true;
    try {
      await CouponAPI.deleteCoupon(id);
    } finally {
      loading.delete = false;
    }
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchList,
    fetchCreate,
    fetchUpdate,
    fetchDelete,
  };
});

export const useCouponStoreHook = () => {
  return useCouponStore(store);
};
